package com.cheys.webapp.dao;

import java.sql.Connection;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.cheys.webapp.util.LogUtil;

public abstract class AbstractDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public int save(String sql) throws Exception{
		int savecount = 0;
		try {
			savecount = getJdbcTemplate().update(sql);
		} catch (Exception e) {
			throw new Exception("数据保存异常"+e);
		} finally{
			closeConnection();
		}
		return savecount;
	}
	public int update(String sql) throws Exception{
		int savecount = 0;
		try {
			savecount = this.jdbcTemplate.update(sql);
		} catch (Exception e) {
			throw new Exception("更新数据异常"+e.getMessage());
		} finally{
			closeConnection();
		}
		return savecount;
	}
	public int delete(String sql) throws Exception{
		int savecount = 0;
		try {
			savecount = this.jdbcTemplate.update(sql);
		} catch (Exception e) {
			throw new Exception("数据删除异常"+e.getMessage());
		} finally{
			closeConnection();
		}
		return savecount;
	}
	
	public void closeConnection(){
		try {
			Connection connection = jdbcTemplate.getDataSource().getConnection();
			if(!connection.isClosed()){
				connection.close();
			}
		} catch (SQLException e) {
			LogUtil.getLogger(this.getClass()).debug("数据库连接关闭异常："+e);
		}
	}
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
}
